package com.bpz.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DESCoder {

	public static final String KEY_STR = "zichengE";
	/*
	 * 加密
	 */
	public static String encrypt(String message, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		return Base64.encodeBase64String(cipher.doFinal(message.getBytes()));
	}
/**
 * 解密
 * @param message
 * @param key
 * @return
 * @throws Exception
 */
	public static String decrypt(String message, String key) throws Exception {

		byte[] bytesrc = Base64.decodeBase64(message);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte);
	}
	public static void main(String[] args) throws Exception {		
		String desc=encrypt("中国",KEY_STR);
		System.out.println(desc);
        desc="JLFZTgQuY+QHkqXyB9TF+wbQ4IA6LXIo9hmjnSm7jZdfm2U0/wso8Q4jyUumbLs0tfI0eDS/9CxK2r39oqahJMuVfgf4oO4Cg1+kN3IIt6OmJ0WLaEtWiQ==";
		 desc=decrypt(desc,KEY_STR);
		
		System.out.println(desc);
		
	}

}